﻿using System.Windows.Forms;
using ComputerVision.BaseForm;
using ComputerVision.Data;
using ComputerVision.Services;
using Autofac;
using ComputerVision.Data.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Collections;
using System.Text;
using System.IO;

namespace ComputerVision.LoaiCoSoForm
{
    public partial class frmBaoCaoChayNo : frmList
    {
        private IService<PhieuDieuTraCoSo> _phieuDieuTraCoSo;
        private readonly IService<LoaiCoSo> _loaiCoSo;
        private readonly IService<Nganh> _nganh;
        private readonly IService<QuanHuyen> _quanHuyen;
        private readonly IService<ChuyenDe> _chuyenDe;

        public frmBaoCaoChayNo()
        {
            InitializeComponent();

            report.AutoGenerateColumns = false;
            report.Columns[1].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopLeft;

            report.Columns[2].DefaultCellStyle.WrapMode = DataGridViewTriState.True;
            report.Columns[2].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopLeft;

            report.Columns[3].DefaultCellStyle.WrapMode = DataGridViewTriState.True;
            report.Columns[3].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopLeft;

            report.Columns[4].DefaultCellStyle.WrapMode = DataGridViewTriState.True;
            report.Columns[4].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopLeft;

            report.Columns[5].DefaultCellStyle.WrapMode = DataGridViewTriState.True;
            report.Columns[5].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopLeft;

            report.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;

            _phieuDieuTraCoSo = Program.Container.Resolve<IService<PhieuDieuTraCoSo>>();
            _loaiCoSo = Program.Container.Resolve<IService<LoaiCoSo>>();
            _nganh = Program.Container.Resolve<IService<Nganh>>();
            _quanHuyen = Program.Container.Resolve<IService<QuanHuyen>>();
            _chuyenDe = Program.Container.Resolve<IService<ChuyenDe>>();

            LoadQuanHuyen();
            LoadChuyenDe();
            LoadLoaiCoSo();
            LoadNganh();
        }

        private void GenerateReport(object sender, System.EventArgs e)
        {   
            BuildReportData();
            SaveAsCSV(report, "D:\\xxx.csv");
        }        

        public void LoadLoaiCoSo()
        {
            var loaiCoSo = _loaiCoSo.ToList().OrderBy(c => c.Ten).ToList();
            loaiCoSo.Insert(0, new LoaiCoSo());
            drlLoaiCoSo.DataSource = loaiCoSo;
            drlLoaiCoSo.DisplayMember = "Ten";
            drlLoaiCoSo.ValueMember = "Id";
        }

        public void LoadQuanHuyen()
        {
            var quanHuyen = _quanHuyen.ToList().OrderBy(q => q.Ten).ToList();
            var toanTinh = new QuanHuyen();            
            toanTinh.Ten = "Toàn tỉnh";
            quanHuyen.Insert(0, toanTinh);
            drlQuanHuyen.DataSource = quanHuyen;
            drlQuanHuyen.DisplayMember = "Ten";
            drlQuanHuyen.ValueMember = "Id";
        }

        public void LoadNganh()
        {
            var nganh = _nganh.ToList().OrderBy(n => n.Ten).ToList();
            nganh.Insert(0, new Nganh());
            drlNganhNghe.DataSource = nganh;
            drlNganhNghe.DisplayMember = "Ten";
            drlNganhNghe.ValueMember = "Id";
        }

        public void LoadChuyenDe()
        {
            var chuyenDe = _chuyenDe.ToList().OrderBy(h => h.Ten).ToList();
            chuyenDe.Insert(0, new ChuyenDe());
            drlChuyenDe.DataSource = chuyenDe;
            drlChuyenDe.DisplayMember = "Ten";
            drlChuyenDe.ValueMember = "Id";
        }

        private void BuildReportData()
        {
            var results = GetData();

            var items = new List<ReportChayNo>();

            Hashtable hash = new Hashtable();

            int numberItem = results.Count;
            if (numberItem == 0)
            {
                report.DataSource = null;
                return;
            }

            progressBar.Value = 1;
            progressBar.Maximum = numberItem;

            if (results.Count > 0)
            {
                foreach (var phieu in results)
                {
                    string quan = phieu.QuanHuyen.Ten;
                    ReportChayNo item = new ReportChayNo();

                    if (hash.ContainsKey(quan))
                    {
                        item = (ReportChayNo)hash[quan];
                        if (phieu.LoaiCoSoId.HasValue)
                        {
                            string loaiCoSo = Convert.ToString(phieu.LoaiCoSo.Ten);
                            if (!string.IsNullOrEmpty(loaiCoSo) && item.LoaiCoSo.IndexOf(loaiCoSo) == -1)
                            {
                                item.LoaiCoSo = string.Concat(item.LoaiCoSo, Environment.NewLine, "- ", loaiCoSo);
                            }
                        }

                        if (phieu.NganhId.HasValue)
                        {
                            string nganh = Convert.ToString(phieu.Nganh.Ten);
                            if (!string.IsNullOrEmpty(nganh) && item.NganhNghe.IndexOf(nganh) == -1)
                            {
                                item.NganhNghe = string.Concat(item.NganhNghe, Environment.NewLine, "- ", nganh);
                            }
                        }

                        if (phieu.NganhId.HasValue && phieu.Nganh.ChuyenDeId.HasValue)
                        {
                            string chuyenDe = Convert.ToString(phieu.Nganh.ChuyenDe.Ten);
                            if (!string.IsNullOrEmpty(chuyenDe) && item.ChuyenDe.IndexOf(chuyenDe) == -1)
                            {
                                item.ChuyenDe = string.Concat(item.ChuyenDe, Environment.NewLine, "- ", chuyenDe);
                            }
                        }

                        foreach (TinhHinhChayNo chayNo in phieu.TinhHinhChayNo)
                        {
                            item.SoVuChay++;

                            item.ThietHaiTaiSan += (double)chayNo.TaiSan.Value;
                            item.ThietHaiNguoiChet += chayNo.Chet.Value;
                            item.ThietHaiNguoiBiThuong += chayNo.BiThuong.Value;
                        }
                    }
                    else
                    {
                        item.QuanHuyen = quan;

                        if (phieu.LoaiCoSoId.HasValue)
                        {
                            string loaiCoSo = Convert.ToString(phieu.LoaiCoSo.Ten);
                            if (!string.IsNullOrEmpty(loaiCoSo))
                            {
                                item.LoaiCoSo = string.Concat("Các loại hình cơ sở:", Environment.NewLine, "- ", loaiCoSo);
                            }
                        }

                        if (phieu.NganhId.HasValue)
                        {
                            string nganh = Convert.ToString(phieu.Nganh.Ten);
                            if (!string.IsNullOrEmpty(nganh))
                            {
                                item.NganhNghe = string.Concat("Các ngày nghề:", Environment.NewLine, "- ", nganh);
                            }
                        }

                        if (phieu.NganhId.HasValue && phieu.Nganh.ChuyenDeId.HasValue)
                        {
                            string chuyenDe = Convert.ToString(phieu.Nganh.ChuyenDe.Ten);
                            if (!string.IsNullOrEmpty(chuyenDe))
                            {
                                item.ChuyenDe = string.Concat("Các chuyên đề:", Environment.NewLine, "- ", chuyenDe);
                            }
                        }

                        foreach (TinhHinhChayNo chayNo in phieu.TinhHinhChayNo)
                        {
                            item.SoVuChay++;

                            item.ThietHaiTaiSan += (double)chayNo.TaiSan.Value;
                            item.ThietHaiNguoiChet += chayNo.Chet.Value;
                            item.ThietHaiNguoiBiThuong += chayNo.BiThuong.Value;
                        }
                        hash[quan] = item;
                    }

                    progressBar.Increment(1);
                }
            }
            
            if (hash.Count > 0)
            {
                var rows = new List<ReportChayNo>();

                foreach (string k in hash.Keys)
                {
                    var temp = (ReportChayNo)hash[k];

                    if(temp.SoVuChay > 0)
                    {
                        temp.TinhHinhChayNo = string.Format("Có tổng số {0} vụ cháy xảy ra trên địa bàn.", temp.SoVuChay);
                        temp.TinhHinhChayNo += string.Format("{0}Thống kê thiệt hại:{0}- Về tài sản: {1} triệu đồng{0}- Số người chết: {2} người{0}- Số người bị thương: {3} người",
                            Environment.NewLine, temp.ThietHaiTaiSan.ToString("#,##0"), temp.ThietHaiNguoiChet, temp.ThietHaiNguoiBiThuong);
                    }
                    else
                    {
                        temp.TinhHinhChayNo = "Không có vụ cháy nào xẩy ra.";
                    }

                    rows.Add(temp);
                }

                report.DataSource = rows;
            }

        }

        private List<PhieuDieuTraCoSo> GetData()
        {
            var quan = drlQuanHuyen.SelectedItem as QuanHuyen;
            var loaiCoSo = drlLoaiCoSo.SelectedItem as LoaiCoSo;
            var nganh = drlNganhNghe.SelectedItem as Nganh;
            var chuyenDe = drlChuyenDe.SelectedItem as ChuyenDe;

            List<PhieuDieuTraCoSo> results = new List<PhieuDieuTraCoSo>();

            if (string.Equals(quan.Ten, "Toàn tỉnh", StringComparison.InvariantCultureIgnoreCase))
            {
                results = _phieuDieuTraCoSo.ToList().Where(p => p.QuanHuyenId.HasValue).ToList();
            }
            else
            {
                results = _phieuDieuTraCoSo.ToList().Where(p => p.QuanHuyenId.HasValue && p.QuanHuyenId.Value == quan.Id).ToList();
            }

            if (!string.IsNullOrEmpty(loaiCoSo.Ten))
            {
                results = results.Where(p => p.LoaiCoSoId.Value == loaiCoSo.Id).ToList();
            }

            if (!string.IsNullOrEmpty(nganh.Ten))
            {
                results = results.Where(p => p.NganhId.Value == nganh.Id).ToList();
            }

            if (!string.IsNullOrEmpty(chuyenDe.Ten))
            {
                results = results.Where(p => p.NganhId.HasValue && p.Nganh.ChuyenDeId.HasValue && p.Nganh.ChuyenDeId == chuyenDe.Id).ToList();
            }

            return results;
        }

        public void SaveAsCSV(DataGridView dgv, string filename)
        {
            string outputStr = string.Empty;
            string headersStr = string.Empty;

            for (int col = 0; col < dgv.Columns.Count; col++)
            {
                headersStr += '\"' + dgv.Columns[col].HeaderText + "\","; // "header",
            }
            outputStr += headersStr + Environment.NewLine; // "header1","header2",[...],CRLF

            for (int row = 0; row <= dgv.RowCount - 1; row++)
            {
                string line = string.Empty;
                for (int cell = 0; cell < dgv.Rows[row].Cells.Count; cell++)
                {
                    line += '\"' + Convert.ToString(dgv.Rows[row].Cells[cell].Value) + "\","; // "cellvalue",
                }
                outputStr += line + Environment.NewLine; // "cellvalue1","cellvalue2",[...],CRLF
            }
            
            using (FileStream fs = new FileStream(filename, FileMode.Create))
            {
                using (StreamWriter bw = new StreamWriter(fs, Encoding.UTF8))
                {
                    bw.Write(outputStr);
                    bw.Flush();
                }
            }
        }
    }
}
